package com.orangelife.mobile.washcar.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.common.sp.CommSp2;
import com.curry.orangelife.mobile.R;
import com.thirdsdk.baidu.AddressListCallBack;
import com.thirdsdk.baidu.MyLocationListener;
import com.orangelife.mobile.common.activity.BaseMapActivity;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.washcar.adapter.WashCarChooseAddressAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 选择洗车的服务地址
 * Created by ${shz} on 2016/1/22.
 */
public class ChooseAddressActivity extends BaseMapActivity implements AddressListCallBack, OnGetPoiSearchResultListener, OnGetSuggestionResultListener {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tvLocation)
    TextView tvLocation;
    @Bind(R.id.tvLocationAddress)
    TextView tvLocationAddress;
    @Bind(R.id.tvConfirm)
    TextView tvConfirm;
    @Bind(R.id.slvList)
    ListView slvList;
    @Bind(R.id.lvSuggestion)
    ListView lvSuggestion;
    @Bind(R.id.llDefaultAddress)
    LinearLayout llDefaultAddress;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    //    @Bind(R.id.etSearch)
//    AutoCompleteTextView etSearch;
    @Bind(R.id.ivSearch)
    ImageView ivSearch;
    @Bind(R.id.ivMapCenter)
    ImageView ivMapCenter;
    private WashCarChooseAddressAdapter washCarChooseAddressAdapter;
    private List<PoiInfo> poiInfoList;
    /**
     * 地址和经纬度
     */
    private String address;
    private String addrLng;
    private String addrLat;
    private String city;
    public static final int NETWORK_ERROR = 1; // 网络错误
    public static final int NETWORK_LOADING = 2; // 加载中
    public static final int NODATA = 3; // 没有数据
    private int currentReqMode = NETWORK_LOADING;

    //地图POI搜索↓↓↓↓↓
    private PoiSearch mPoiSearch = null;
    private SuggestionSearch mSuggestionSearch = null;
    //    private BaiduMap mBaiduMap = null;
    private List<String> suggest;

    /**
     * 搜索关键字输入窗口
     */
    private AutoCompleteTextView keyWorldsView = null;
    private ArrayAdapter<String> sugAdapter = null;
    private int loadIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_address);
        ButterKnife.bind(this);
        currentReqMode = NETWORK_LOADING;
        initView();
        initMap();
        initMapSearch();
//        init(26.100794,119.282305);
        addItemClickListener();
        setImagev(ivMapCenter);
    }

    private void initMapSearch() {
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.etSearch);
        sugAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line);
        keyWorldsView.setAdapter(sugAdapter);
        keyWorldsView.setThreshold(1);

        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        keyWorldsView.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }
                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(city));
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isConnected(false)) {
            showProgress();
            registerReceiver(handler, 1);
        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }

    private void showProgress() {
        if (currentReqMode == NETWORK_LOADING) {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        }
    }

    private void dismissProgress() {
        if (currentReqMode == NETWORK_LOADING) {
            emptyLayout.dismiss();
        }
    }

    /**
     * 添加list的item监听
     */
    private void addItemClickListener() {
        slvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                String address = poiInfoList.get(position).address;
                String name = poiInfoList.get(position).name;
                addrLat = String.valueOf(poiInfoList.get(position).location.latitude);
                addrLng = String.valueOf(poiInfoList.get(position).location.longitude);
                bundle.putString("address", address + name);
                bundle.putString("addrLat", addrLat);
                bundle.putString("addrLng", addrLng);
                intent.putExtras(bundle);
                setResult(2, intent);
                finish();
            }
        });
    }

    @Override
    public MyLocationListener initListener(MyLocationListener myListener) {
        return new MyLocationListener(ChooseAddressActivity.this);
    }

    /**
     * 初始化界面信息
     */
    private void initView() {
        city = CommSp2.getCityName();
        tvTitle.setText("选择地址");
        llDefaultAddress.setOnClickListener(listener);
        poiInfoList = new ArrayList<>();
        washCarChooseAddressAdapter = new WashCarChooseAddressAdapter(this, poiInfoList);
        slvList.setAdapter(washCarChooseAddressAdapter);
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentReqMode = NETWORK_LOADING;

            }
        });

        ivSearch.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            if (keyWorldsView.getVisibility() == View.GONE) {
                                                tvTitle.setVisibility(View.GONE);
                                                keyWorldsView.setAnimation(AnimationUtils.makeInAnimation(ChooseAddressActivity.this, false));
                                                keyWorldsView.setVisibility(View.VISIBLE);
                                            } else {
                                                closeKeybord();
                                                if (lvSuggestion.getVisibility() == View.VISIBLE) {
                                                    suggest.clear();
                                                    sugAdapter.notifyDataSetChanged();
                                                    lvSuggestion.setVisibility(View.GONE);
                                                }
                                                keyWorldsView.setText("");
//                    keyWorldsView.setAnimation(AnimationUtils.makeOutAnimation(ChooseAddressActivity.this,true));
                                                keyWorldsView.setVisibility(View.GONE);
                                                tvTitle.setVisibility(View.VISIBLE);
                                            }
                                        }
                                    }

        );
    }

    private void closeKeybord() {
        if (getCurrentFocus() != null) {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private boolean isFirstLoc = true;
    /**
     * 百度地图获取当前的地址定位
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (isFirstLoc) {
                        Map<String, Object> map = (Map<String, Object>) msg.obj;
                        if (map != null) {
                            double lat = Double.valueOf(map.get("lat").toString());
                            double lon = Double.valueOf(map.get("lon").toString());
                            init(lat, lon);
                            isFirstLoc = false;
                        }
                    }
                    break;
            }
        }
    };


    private void initMap() {
        Log.e("initMap", "initMap");
        initMap(R.id.bmapView);
        setAddressListCallBack(this);
    }

    @Override
    public void getAddressList(List<PoiInfo> poiInfoList, LatLng latLng, String address) {
        this.poiInfoList = poiInfoList;
        this.address = address;
        if (poiInfoList != null) {
            dismissProgress();
            addrLat = String.valueOf(latLng.latitude);
            addrLng = String.valueOf(latLng.longitude);
            tvLocation.setText("当前：" + address);
            tvLocationAddress.setText(address);
            washCarChooseAddressAdapter.setList(poiInfoList);
            washCarChooseAddressAdapter.notifyDataSetChanged();
        } else {
            emptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }

    /**
     * 点击事件
     */
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                //点击默认的地址
                case R.id.llDefaultAddress:
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("address", address);
                    bundle.putString("addrLat", addrLat);
                    bundle.putString("addrLng", addrLng);
                    intent.putExtras(bundle);
                    setResult(2, intent);
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        mPoiSearch.destroy();
        mSuggestionSearch.destroy();
        super.onDestroy();
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null
                || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            List<PoiInfo> listPoi = result.getAllPoi();
            init(listPoi.get(0).location.latitude, listPoi.get(0).location.longitude);
            getAddressList(listPoi, listPoi.get(0).location, listPoi.get(0).address);
//            getAddressList(listPoi,);
//            mBaiduMap.clear();
//            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
//            mBaiduMap.setOnMarkerClickListener(overlay);
//            overlay.setData(result);
//            overlay.addToMap();
//            overlay.zoomToSpan();
            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }

    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        if (res == null || res.getAllSuggestions() == null) {
            return;
        }
        suggest = new ArrayList<String>();
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null) {
                suggest.add(info.key);
            }
        }
        sugAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, suggest);
        lvSuggestion.setVisibility(View.VISIBLE);
        lvSuggestion.setAdapter(sugAdapter);
        sugAdapter.notifyDataSetChanged();
        lvSuggestion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String address = suggest.get(position);
                mPoiSearch.searchInCity((new PoiCitySearchOption()).city(city).keyword(address));
                keyWorldsView.setText("");
                closeKeybord();
                tvTitle.setVisibility(View.VISIBLE);
                keyWorldsView.setVisibility(View.GONE);
                lvSuggestion.setVisibility(View.GONE);
            }
        });
    }
}

